#coding: utf-8

import nonebot as nb
import aiocqhttp
import random
import os
import pickle

from .command import *
from .config import *

bot = nb.get_bot()

def splitString(string: str) -> list:
    """
    避免字符串过长所定义的一个函数...

    string:     target string
    """
    info = string.split('\n')
    targetList = []
    if len(info) > 16:
        for i in range(len(info) // 16 + 1):
            tempInfo = '\n'.join(info[i * 16:(i + 1) * 16])
            if i != 0:
                tempInfo = '** 接上面 **\n' + tempInfo
            if i != (len(info) // 16):
                tempInfo = tempInfo + "\n** 接下面 **"
            targetList.append(tempInfo)
    else:
        targetList = ['\n'.join(info), ]
    return targetList

def isRepeat(prob: int) -> bool:
    """
    判断是否复读的函数...
    """
    return True if random.random() * 100 < prob else False

def sortRule(item: list) -> int:
    return list(item)[1]

async def repeatJudge(event: aiocqhttp.Event) -> None:
    """
    对整个字典进行比对的函数...

    event:  aiocqhttp.Event
    """
    global bot, KeywordsRepeatProb, GroupRepeatProb
    theMessage = event.raw_message
    group_id = event.group_id
    tempDict = {
        'abs': {
        },
        'inc': {
        }
    }
    for the_type in ['all', group_id]: # 这样能够保证local的优先级高于globa的优先级
        for method in ['abs', 'inc']:
            for item in KeywordsRepeatProb[the_type][method].keys():
                tempDict[method][item] = KeywordsRepeatProb[the_type][method][item]
    if theMessage in tempDict['abs'].keys():
        if isRepeat(tempDict['abs'][theMessage]):
            await bot.send_msg(group_id=group_id, message=theMessage)
            return None
    incList = list(tempDict['inc'].items())
    incList.sort(key=sortRule, reverse=True) # 复读概率高的优先级高
    for item, prob in incList:
        if item in theMessage:
            if isRepeat(prob):
                await bot.send_msg(group_id=group_id, message=theMessage)
                return None
    if isRepeat(GroupRepeatProb[group_id]): # 比较群的概率
        await bot.send_msg(group_id=group_id, message=theMessage)
        return None

def isCommand(string: int) -> bool:
    """
    判断string是否为命令
    """
    theMessage = string
    for item in COMMANDS:
        if item in theMessage.lower():
            return True
    return False



def theData(mode: str) -> bool:
    """
    处理数据

    mode:   'save' or 'load'
    """
    global NEED_SAVE
    for i in NEED_SAVE:
        exec(f"global {i}")
    Location = os.getcwd()
    os.chdir(r"C:\awesome\plugins\repeat")
    fileName = 'mainConfig.dat'
    if mode == 'load' and os.path.isfile(fileName):
        return False
    try:
        if mode == 'save':
            theFile = open(fileName, 'w', encoding='gb18030')
            for i in NEED_SAVE:
                theCmd = f'print("{i} = {eval(i)}", file=theFile, flush=True)'
                exec(theCmd)
            theFile.close()
        elif mode == 'load':
            theFile = open(fileName, 'r', encoding='gb18030')
            exec(theFile.read().decode('gb18030'))
            theFile.close()
        else:
            raise KeyError(mode)
        os.chdir(Location)
        return True
    except Exception as e:
        nb.logger.warn(__plugin_name__ + f'.theData: {e.__repr__()}')
        return False

@bot.on_notice('group_increase')
async def syncInfo(event: aiocqhttp.Event) -> None:
    """
    当加入群后自动更新所有数据, 并且改群名片, 提示超级管理员
    """
    global bot, KeywordsRepeatProb, SUPERUSERS, GroupRepeatProb, DEFAULT_GROUP_PROB, GODUSER
    KeywordsRepeatProb[event.group_id] = {'abs':{}, 'inc': {}}
    SUPERUSERS[event.group_id] = set()
    GroupRepeatProb[event.group_id] = DEFAULT_GROUP_PROB
    await bot.send_msg(group_id=event.group_id, message="大家好, 我是一只屑bot.")
    await bot.set_group_card(group_id=event.group_id, user_id=event.self_id, card="只会复读的屑复读稽")
    await bot.send_msg(user_id=GODUSER, message="Bot 已加入 {} 群.".format(event.group_id))
    